﻿using System;
using Microsoft.Practices.ObjectBuilder;

namespace Microsoft.Practices.CompositeUI.BuilderStrategies
{
    /// <summary>
    /// 	An ObjectBuilder strategy which notifies CompositeApplication when an object is fully built so that the <see cref = "WorkItem" /> can be notified.
    /// </summary>
    public class ObjectBuiltNotificationStrategy : BuilderStrategy
    {
        #region Fields & Properties

        private ObjectBuiltNotificationPolicy _policy;

        #endregion

        #region Build Up

        /// <summary>
        /// 	See <see cref = "IBuilderStrategy.BuildUp" /> for more information.
        /// </summary>
        public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
        {
            var workItem = context.Locator.Get<WorkItem>(new DependencyResolutionLocatorKey(typeof (WorkItem), null));
            Action<object> itemNotify;
            if (_policy == null)
            {
                _policy = context.Policies.Get<ObjectBuiltNotificationPolicy>(null, null);
            }
            if (workItem != null && !ReferenceEquals(workItem, existing) && _policy.AddedDelegates.TryGetValue(workItem, out itemNotify))
            {
                itemNotify(existing);
            }
            return base.BuildUp(context, typeToBuild, existing, idToBuild);
        }

        #endregion

        #region Tear Down

        /// <summary>
        /// 	See <see cref = "IBuilderStrategy.TearDown" /> for more information.
        /// </summary>
        public override object TearDown(IBuilderContext context, object item)
        {
            var workItem = context.Locator.Get<WorkItem>(new DependencyResolutionLocatorKey(typeof (WorkItem), null));
            Action<object> itemNotify;
            if (workItem != null && _policy.RemovedDelegates.TryGetValue(workItem, out itemNotify))
            {
                itemNotify(item);
            }
            return base.TearDown(context, item);
        }

        #endregion
    }
}